package com.tyc.tool;

import java.util.concurrent.*;

/**
 * 两个线程有一个没有执行exchange()方法，则会一直等待
 * 如果担心有特殊情况发生，避免一直等待，可以使用exchange(V x, long timeOut, TimeUnit unit) 设置最大等待时长。
 *
 * @author tyc
 * @version 1.0
 * @date 2023-01-13 10:44:08
 */
public class ExchangerTest {
    private static final Exchanger<String> exchanger = new Exchanger<>();
    private static final ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        executor.execute(()->{
            try {
                String A = "1288"; // A员工计算公司流水值
                String B = exchanger.exchange(A);
                if(A.equals(B)){
                    System.out.println("A:结果一致");
                }else {
                    System.out.println("结果异常");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executor.execute(()->{
            try {
                String B = "1288"; // B员工计算公司流水值
                String A = exchanger.exchange(B);
                if(B.equals(A)){
                    System.out.println("B:结果一致");
                }else {
                    System.out.println("结果异常");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
